package gui;

import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;

import java.net.URL;
import db.*;
import util.Util;

import ptolemy.actor.gui.*;

//////////////////////////////////////////////////////////////////////////
//// VerifierApplicationFrame
/**

@author Ivan Jeukens
@version v 0.1 02/10/2002
*/
public class VerifierApplicationFrame extends JFrame {

    public VerifierApplicationFrame() {
        super();

        setSize(500, 600);
        setTitle("Data Bases");

        String gifpath = new String(System.getProperty("user.home") + 
            "/ptij/icons/uspIcon.gif");
        try {
            URL url = new URL("file:" + gifpath);
            Toolkit tk = Toolkit.getDefaultToolkit();
            Image im = tk.createImage(url);
            setIconImage(im);
        }
        catch(Exception ex) {
            System.out.println(ex);
        }
	    _mainPanel = new JPanel(new BorderLayout());

        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new BoxLayout(buttonPanel, 
            BoxLayout.X_AXIS));
        gifpath = new String(System.getProperty("user.home") + 
                "/ptij/verifier/gifs/");

        ImageIcon img = new ImageIcon(gifpath + "open.gif");
        JButton button = new JButton(img);
        button.setToolTipText("View Data");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                _viewAction();
	    }
        });
        buttonPanel.add(button);
        
        img = new ImageIcon(gifpath + "rem.gif");
        button = new JButton(img);
        button.setToolTipText("Remove Data");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                _removeAction();
	    }
        });
        buttonPanel.add(button);
        _mainPanel.add(buttonPanel, BorderLayout.NORTH);

        getContentPane().add(_mainPanel, BorderLayout.CENTER);

        //_messagesFrame = new MessagesFrame();
        //_progressDialog = new ProgressDialog(this);

        JMenuBar bar = new JMenuBar();
        setJMenuBar(bar);
        
        JMenu menu = new JMenu("Action");
        MenuListener menuListener = new MenuListener();
        
        JMenuItem item = new JMenuItem("View Data");
        item.setActionCommand("View Data");
        item.addActionListener(menuListener);
        menu.add(item);
        
        item = new JMenuItem("Remove Data");
        item.setActionCommand("Remove Data");
        item.addActionListener(menuListener);
        menu.add(item);
        
        menu.addSeparator();
        
        item = new JMenuItem("Close");
        item.setActionCommand("Close");
        item.addActionListener(menuListener);
        menu.add(item);
        
        bar.add(menu);
        
        initialize();
    }

    public static final Color BackgroundColor = new Color(0xe5e5e5);

    ///////////////////////////////////////////////////////////////////
    ////                         public methods                   ////

    public void initialize() {
        _classDB = new ClassDB();
        _atomicActorDB = new AtomicActorDB();
        _compositeActorDB = new CompositeActorDB();

        _basePath = new String("/home/ivan/.ptijVerifier/");
        _classDB.setBasePath("/home/ivan/.ptijVerifier/");
        _atomicActorDB.setBasePath("/home/ivan/.ptijVerifier/");
        _compositeActorDB.setBasePath("/home/ivan/.ptijVerifier/");

        _classDB.setAtomicActorDataBase(_atomicActorDB);
        _atomicActorDB.setClassDataBase(_classDB);
        _compositeActorDB.setAtomicActorDataBase(_atomicActorDB);

        _classDB.load();
        _atomicActorDB.load();
        _compositeActorDB.load();
        
        _buildTabbedPane();
    }

    public void setDirectory(ModelDirectory directory) {
        _directory = directory;
    }

    public void setConfiguration(Configuration configuration) {
        _configuration = configuration;
    }

    /*
    public LinkedList getSelectedMocs() {
        if(_mocDialog == null) return null;
        return _mocDialog.getSelectedMoCs();
    }*/

    ///////////////////////////////////////////////////////////////////
    ////                         protected methods                 ////

    /*
    protected void _addMenus() {
        super._addMenus();

        JMenuItem[] ViewMenuItems = {
            new JMenuItem("Available MoCs")                                                          
        };

        _viewMenu = new JMenu("View");
        ViewMenuListener mml = new ViewMenuListener(this);
        for(int i = 0; i < ViewMenuItems.length; i++) {
            ViewMenuItems[i].setActionCommand(
                ViewMenuItems[i].getText());
            ViewMenuItems[i].addActionListener(mml);
            _viewMenu.add(ViewMenuItems[i]);
        }        

        _menubar.add(_viewMenu);
    }*/

    ///////////////////////////////////////////////////////////////////
    ////                         protected variables               ////
        
    // protected JMenu _viewMenu;

    ///////////////////////////////////////////////////////////////////
    ////                         private   methods                 ////

    private void _openEffigy(String name, String url, boolean composite) {
        String s = Util.removeDot(new String(url + name));
        VerifierEffigy effigy = (VerifierEffigy) _directory.getEntity(s);
        if(effigy == null) {
            EffigyFactory factory =
                (EffigyFactory) _configuration.getEntity("effigyFactory");
            EffigyFactory verifierFactory =
                (EffigyFactory) factory.getEntity("Verifier");
            try {
                effigy = (VerifierEffigy) verifierFactory.createEffigy(_directory);
                if(composite) {
                    effigy.loadCompositeActor(name);
                }
                else {
                    // effigy.loadAtomicActor(name);
                }
                effigy.setName(s);
            }
            catch(Exception ex) {
                System.out.println("Nao consegui criar a VerifierEffigy -> " + ex);
            }
        }
        effigy.showTableaux();
    }

    private void _buildTabbedPane() {
        _tablePane = new JTabbedPane();

        final DBTableModel compositeActorTableModel = _compositeActorDB.getTableModel();
        _compositeActorTable = new JTable(compositeActorTableModel);
        _compositeActorTable.addMouseListener(new MouseListener() {
            public void mouseClicked(MouseEvent e) {
                if(e.getClickCount() == 2) {
                    Point p = e.getPoint();
                    int row = _compositeActorTable.rowAtPoint(p);
                    dbInfoSummary sum = compositeActorTableModel.getSummaryAt(row);

                    _openEffigy(sum.getName(), sum.getURL().toString(), true);
                    _previousRow = row;
                }
                else
                if(e.getClickCount() == 1) {
                    Point p = e.getPoint();
                    int row = _compositeActorTable.rowAtPoint(p);
                    if(row == _previousRow) {
                        _compositeActorTable.clearSelection();
                        _previousRow = -1;
                    }
                    else {
                        _previousRow = row;
                    }
                }
            }

            private int _previousRow = -1;
                        
            public void mousePressed(MouseEvent e) { }
            public void mouseReleased(MouseEvent e) { }
            public void mouseEntered(MouseEvent e) { }
            public void mouseExited(MouseEvent e) { }
        });

        TableColumn c = _compositeActorTable.getColumnModel().getColumn(0);
        c.setPreferredWidth(10);
        c = _compositeActorTable.getColumnModel().getColumn(0);
        c.setPreferredWidth(100);
        _compositeActorTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        JScrollPane sc = new JScrollPane(_compositeActorTable);
        _tablePane.addTab("Composite Actors", null, sc, "Specifications");

        DBTableModel atomicActorTableModel = _atomicActorDB.getTableModel();
        _atomicActorTable = new JTable(atomicActorTableModel);
        /*
        _actorsTable.addMouseListener(new MouseListener() {
            public void mouseClicked(MouseEvent e) {
                if(e.getClickCount() == 2) {
                    Point p = e.getPoint();
                    int row = _actorsTable.rowAtPoint(p);                    
                    ActorInfo info = (ActorInfo) _actorsTableModel.getDBInfoAt(row);

                    _messagesFrame.setTitle("Messages for " + info.getName());
                    _messagesFrame.displayInfo((dbInfo) info);
                    _messagesFrame.show();

                    _previousRow = row;
                }                
                else
                if(e.getClickCount() == 1) {
                    Point p = e.getPoint();
                    int row = _actorsTable.rowAtPoint(p);
                    if(row == _previousRow) {
                        _actorsTable.clearSelection();
                        _previousRow = -1;
                    }
                    else {                    
                        _previousRow = row;
                    }                    
                }
            }
                
            private int _previousRow = -1;
                                        
            public void mousePressed(MouseEvent e) { }
            public void mouseReleased(MouseEvent e) { }
            public void mouseEntered(MouseEvent e) { }
            public void mouseExited(MouseEvent e) { }
        }); */

        c = _atomicActorTable.getColumnModel().getColumn(0);
        c.setMinWidth(0);
        c.setMaxWidth(1000);
        c.setPreferredWidth(2);

        _atomicActorTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        sc  = new JScrollPane(_atomicActorTable);
        _tablePane.addTab("Atomic Actors", null, sc, "Actors");
        _mainPanel.add(_tablePane, BorderLayout.CENTER);
    }

    /*
    private void _analyzeAction() {
        // determina qual e a tabela que o usuario esta vendo, ator ou spec
        int index = _tablePane.getSelectedIndex();
        JTable table = null;
        if(index == 0) {
            table = _specsTable;
        }
        else
        if(index == 1) {
            table = _actorsTable;
        }
        
        if(table != null) {
            // depois, tenho que implementar multiplas selecoes
            int row = table.getSelectedRow();
            if(row != -1) {
                String s = (String) table.getValueAt(row, 1);
                VerifierEffigy ef = (VerifierEffigy) getEffigy();
                dbInfo info;
                if(index == 0) {
                    info = ef.getSpecInfo(s);
                }
                else {
                    info = ef.getActorInfo(s);
                }
                if(info.isOutdated()) {
                    //_progressDialog.show();
                    info.rebuild();
                }
               
                
                return;
            }
        }*/

/*        
        JFileChooser fc = new JFileChooser(".");
        int returnVal = fc.showOpenDialog(this);
        if(returnVal == JFileChooser.APPROVE_OPTION) {
            File f = fc.getSelectedFile();
            if(f.isFile()) {
                String n = f.getAbsolutePath();
                StringTokenizer st = new StringTokenizer(n, ".");
                String s = null;
                while(st.hasMoreTokens()) {
                    s = st.nextToken();
                }

                if(s != null) {
                    LinkedList mocs = null;
                    if(_mocDialog != null) {
                        mocs = _mocDialog.getSelectedMoCs();
                    }
                    if(mocs == null || mocs.size() == 0) {
                        JOptionPane.showMessageDialog(null,
                            "No MoC has been selected", "Error",
                            JOptionPane.ERROR_MESSAGE);
                         return;
                    }

                    if(s.equals("xml")) {
                        VerifierEffigy ef = (VerifierEffigy) getEffigy();
                        //_progressDialog.show();
                        ef.analyzeSpecFromFile(n, 
                            f.getParentFile().getAbsolutePath(), mocs);
                    }
                    else
                    if(s.equals("java")) {
                        VerifierEffigy ef = (VerifierEffigy) getEffigy();
                        //_progressDialog.show();
                        ef.analyzeActorFromFile(n, mocs);
                    }
                    else {
                        JOptionPane.showMessageDialog(null,
                            "Cannont analyze: unrecognized file type", "Error",
                            JOptionPane.ERROR_MESSAGE);
                    }
                }                
            }
        } */
        //_progressDialog.hide();
    // }
        
    /*
    public void _loadAction() {
        JFileChooser fc = new JFileChooser(".");
        int returnVal = fc.showOpenDialog(this);
        if(returnVal == JFileChooser.APPROVE_OPTION) {
            File f = fc.getSelectedFile();
            if(f.isFile()) {                
                String n = f.getAbsolutePath();
                // determina a extensao do arquivo
                StringTokenizer st = new StringTokenizer(n, ".");
                String s = null;
                while(st.hasMoreTokens()) {
                    s = st.nextToken();
                }
                if(s != null) {
                    // uma especificacao
                    if(s.equals("xml")) {
                        VerifierEffigy ef = (VerifierEffigy) getEffigy();
                        //_progressDialog.show();                        
                        ef.loadSpec(n, f.getParentFile().getAbsolutePath());                    
                    }
                    else
                    // um ator
                    if(s.equals("java")) {
                        VerifierEffigy ef = (VerifierEffigy) getEffigy();
                        //_progressDialog.show();
                        ef.loadActor(n);
                    }
                    else {
                        JOptionPane.showMessageDialog(null,
                            "Cannont load: unrecognized file type", "Error",
                            JOptionPane.ERROR_MESSAGE);
                    }
                }
            }
        }
    }
*/
    public void _viewAction() {
        
    
    }

    public void _removeAction() {

    }

/*    
    public void _saveDBAction() {
        VerifierEffigy ef = (VerifierEffigy) getEffigy();
        ef.saveDB();
    }
    
    public void _updateDBAction() {
        
    }
    
    private void _initializeMoCDialog() {
        _mocDialog = new MoCDialog(this);
        VerifierEffigy ef = (VerifierEffigy) getEffigy();
        Iterator moc = ef.mocIterator();
        LinkedList tmp = new LinkedList();
        while(moc.hasNext()) {
            MoCVerifier ve = (MoCVerifier) moc.next();
            tmp.add(ve.getName());            
        }
        _mocDialog.setMoCs(tmp);
    }        
    */
    
    ///////////////////////////////////////////////////////////////////
    ////                         private variables               ////
    
    private JTable _atomicActorTable;
    private JTable _compositeActorTable;
    private JPanel _mainPanel;
    //private MoCDialog _mocDialog;
    //private ProgressDialog _progressDialog;
    //private MessagesFrame _messagesFrame;
    private JTabbedPane _tablePane;
 
    //private DBTableModel _actorsTableModel;
    //private DBTableModel _specsTableModel;
    
    private ClassDB _classDB;
    private AtomicActorDB _atomicActorDB;
    private CompositeActorDB _compositeActorDB;
    private String _basePath;

    private ModelDirectory _directory;
    private Configuration _configuration;

    ///////////////////////////////////////////////////////////////////
    ////                         inner classes                     ////
    
    class MenuListener implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            JMenuItem target = (JMenuItem) e.getSource();
            String actionCommand = target.getActionCommand();
            
            if(actionCommand.equals("Close")) {
                hide();
            }
            else
            if(actionCommand.equals("View Data")) {

            }
            else
            if(actionCommand.equals("Remove Data")) {

            }
        }
    }

    /*
    public class ViewMenuListener implements ActionListener {

        public ViewMenuListener(VerifierFrame parent) {
            _parent = parent;
        }

        public void actionPerformed(ActionEvent e) {
            JMenuItem target = (JMenuItem) e.getSource();
            String actionCommand = target.getActionCommand();
            if(actionCommand.equals("Available MoCs")) {
                if(_mocDialog == null) {                                           
                    _mocDialog = new MoCDialog(_parent);
                    VerifierEffigy ef = (VerifierEffigy) getEffigy();
                    Iterator moc = ef.mocIterator();
                    LinkedList tmp = new LinkedList();
                    while(moc.hasNext()) {
                        MoCVerifier ve = (MoCVerifier) moc.next();
                        tmp.add(ve.getName());            
                    }
                    _mocDialog.setMoCs(tmp);                                
                }                                
                _mocDialog.show();                
            }
        }

        private VerifierFrame _parent;
    } */       
}
